package it.crosato.stage.server.model.phylogeny;

import java.awt.Graphics;

public class ClusterUPGMA extends Cluster {
	int lab;			// Identificatore cluster
	int card;                 // Il numero di organismi in un cluster
	String nome="";
	double height;		// il peso di un nodo
	ClusterUPGMA left, right;	// Figli desto sinistro nullo
	double[] dmat;		// Distanze ai nodi numerati più bassi o null
	
	public ClusterUPGMA(int lab, double[] dmat, String org) {	
		this.lab = lab + 1;
		nome =org;
		card = 1;
		this.dmat = dmat;
	}

	public ClusterUPGMA(int lab, ClusterUPGMA left, ClusterUPGMA right, double height,
			double[] dmat) {
		this.lab = lab + 1;
		this.left = left;
		this.right = right;
		card = left.card + right.card;
		this.height = height;
		this.dmat = dmat;
	}

	public boolean live()
	{ return dmat != null; }

	public void kill()
	{ dmat = null; }

	public void print()
	{ print(0); }

	void print(int n) {
		if (right != null)
			right.print(n + 6);
		if (left != null)
			left.print(n + 6);
	}

	public void draw(Graphics g, int w, int h) {
		draw(g, w, h, 0, (double)w/card, (double)(h-50)/height, 10);
	}

	// Disegna un albero e ritorna la cordinata x della radice

	public int draw(Graphics g, int w, int h, int leftcard,
			double xsc, double ysc, int fromy) {
		if (left != null && right != null) {	// Nodo interno
			int y = (int)(h - 30 - height * ysc);
			int leftx  = left.draw(g, w, h, leftcard, xsc, ysc, y);
			int rightx = right.draw(g, w, h, leftcard+left.card, xsc, ysc, y);
			g.drawLine(leftx, y, rightx, y);
			int x = (leftx + rightx) / 2;
			g.drawLine(x, y, x, fromy);
			g.fillOval(x-4, y-4, 8, 8);
			return x;
		} else {					// foglia
			int x = (int)((leftcard + 0.5) * xsc);
			g.drawLine(x, h-30, x, fromy);
			g.fillOval(x-4, h-30-4, 8, 8);
			g.drawString(nome, x-5, h-10);

			return x;
		}
	}
}
